const express = require('express');
const ReactSSR = require('react-dom/server');

// const fs = require('fs');
const path = require('path');
require('./ignorejs')();


const isProduct = process.env.NODE_ENV === 'production';

const app = express();

if (isProduct) {
  const serverEntry = require('../dist/server-entry').default; // eslint-disable-line
  app.use('/public', express.static(path.join(__dirname, '../dist')));
  app.use((req, res) => {
    res.write(`<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="theme-color" content="#000000">
        <meta name="keywords" content="SSR">
      </head>
      <body>
        <noscript>
          You need to enable JavaScript to run this app.
        </noscript>
        <div id="root">`);
    const markupStream = ReactSSR.renderToNodeStream(serverEntry);
    markupStream.pipe(res, { end: false });
    markupStream.on('end', () => {
      res.end();
    });
  });
} else {
  const devStatic = require('./util/dev-static'); // eslint-disable-line
  devStatic(app);
}


// app.get('*', (req, res) => {
//   const appString = ReactSSR.renderToString(serverEntry);
//   res.send(template.replace('<div id="root"></div>', appString));
// });

app.listen(3333, () => {
  console.log('server is listening on 3333');
});
